<template>
  <el-dialog
    :title="$t('msg.excel.roleDialogTitle')"
    v-model="modelValue"
    @close="closed"
  >
    <el-radio-group v-model="adminRoleValue">
      <el-radio
        v-for="item in allRoleList"
        :key="item.id"
        :label="item.title"
      ></el-radio>
    </el-radio-group>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closed">{{ $t('msg.universal.cancel') }}</el-button>
        <el-button type="primary" @click="onConfirm">{{
          $t('msg.universal.confirm')
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref,onMounted } from 'vue'
import { roleList,userRoles ,updateRole} from '@/api/user-manage'
import { watchSwitchLang } from '@/utils/i18n'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  userId: {
    type: String,
    required: true
  }
})

const emits = defineEmits(['updateModelValue', 'updateRole'])

// 所有角色
const allRoleList = ref([])
// 获取所有角色数据的方法
const getListData = async () => {
  const res = await roleList()
  allRoleList.value = res.findData
}
getListData()
watchSwitchLang(getListData)

// 当前用户的角色
const adminRoleValue = ref('')
// 获取当前用户的角色
const getUserRoles = async () => {
  const res = await userRoles({id:props.userId})
  adminRoleValue.value = res.role
}

/**
  确定按钮点击事件
 */
const i18n = useI18n()
const onConfirm = async () => {
  // 处理数据结构
  // const roles = adminRoleValue.value.map(title => {
  //   return allRoleList.value.find(role => role.title === title)
  // })

  await updateRole({id:props.userId, roles:adminRoleValue.value})

  ElMessage.success(i18n.t('msg.role.updateRoleSuccess'))
  closed()
  // 角色更新成功
  emits('updateRole')
}

/**
 * 关闭
 */
const closed = () => {
  emits('updateModelValue', false)
}
onMounted(()=>{
  if(props.userId){
    getUserRoles()
  }
})
</script>

<style lang="scss" scoped></style>
